//
//  NewsShowViewController.m
//  BasketballClub
//
//  Created by David on 16/1/8.
//  Copyright © 2016年 孙鸿吉. All rights reserved.
//

#import "NewsShowViewController.h"
#import "NewsShowView.h"
#import "NewsHandle.h"
#import <UMSocial.h>
#import "NewsModel.h"
#import <AVOSCloud.h>
#import "TalkingViewController.h"
#import "RegistViewController.h"
#import "FindPWDViewController.h"
#import "NewsTableViewCell.h"
@interface NewsShowViewController ()<UIWebViewDelegate,UIGestureRecognizerDelegate>
{
    NSInteger _differentEventNumber;
}
@property(nonatomic,strong)NewsShowView *newsShowView;
@end

@implementation NewsShowViewController

-(void)loadView
{
    self.newsShowView = [[NewsShowView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.newsShowView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"详情";
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.newsShowView allViewsWithModel:self.model];
    [[self navigationController] setNavigationBarHidden:YES animated:YES];
    

    NSURL *url = [NSURL URLWithString:self.webViewUrl];
    
    //设置代理
    self.newsShowView.newsShowWebview.delegate = self;
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.newsShowView.newsShowWebview loadRequest:request];
    self.newsShowView.newsShowWebview.scalesPageToFit = YES;
    //添加手势
    UIScreenEdgePanGestureRecognizer *edgeGR = [[UIScreenEdgePanGestureRecognizer alloc]initWithTarget:self action:@selector(edgeGR)];
    [self.newsShowView.newsShowWebview addGestureRecognizer:edgeGR];
    self.newsShowView.newsShowWebview.userInteractionEnabled = YES;
    edgeGR.edges = UIRectEdgeLeft;
    
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGR)];
    [self.newsShowView.loginPresentView addGestureRecognizer:panGR];
    self.newsShowView.loginPresentView.userInteractionEnabled = YES;
    panGR.delegate = self;
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCollectState:) name:@"collectState" object:self.newsShowView.rightButton];
    //登陆按钮方法
    [self.newsShowView.loginButton addTarget:self action:@selector(loginButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //注册按钮方法
    [self.newsShowView.registButton addTarget:self action:@selector(registButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //忘记密码按钮方法
    [self.newsShowView.findPWDButton addTarget:self action:@selector(findPWDButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    //分享图片
    self.shareImage = [UIImage imageNamed:@"app"];
    //左侧返回按钮
    [self.newsShowView.leftButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //右侧收藏按钮
    [self.newsShowView.rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //分享按钮
    [self.newsShowView.shareButton addTarget:self action:@selector(shareOtherone) forControlEvents:UIControlEventTouchUpInside];
    //喜欢按钮
    [self.newsShowView.likeButton addTarget:self action:@selector(likeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //评论按钮
    [self.newsShowView.talkButton addTarget:self action:@selector(talkButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - 界面出现方法
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    //喜欢的个数
    AVUser *current = [AVUser currentUser];
    //判断收藏
    //已收藏方法(收藏过得再次进入不在能收藏)
    if (current != nil) {
        AVQuery *collectQuery = [AVQuery queryWithClassName:@"celloct"];
        NSString *collectStr = [NSString stringWithFormat:@"collect%@%@",self.model.iD,current.username];
        [collectQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            if (object != nil) {
                NSString *collectState = [object objectForKey:collectStr];
                if ([collectState isEqualToString:@"isCollect"]) {
                    [self.newsShowView.rightButton setImage:[UIImage imageNamed:@"shoucangle2@2x"] forState:UIControlStateNormal];
                    self.newsShowView.rightButton.userInteractionEnabled = NO;
                }
            }
        }];
    }
    AVQuery *query = [AVQuery queryWithClassName:@"NewsLike"];
    NSString *likeCount = [NSString stringWithFormat:@"likeCount%@",self.model.iD];
    NSString *islike = [NSString stringWithFormat:@"isLike%@%@",self.model.iD,current.username];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        if (object != nil) {
            NSInteger like = [[object objectForKey:likeCount]integerValue];
            NSString *likeState = [object objectForKey:islike];
            if ([likeState isEqualToString:@"like"] && current != nil) {
                [self.newsShowView.likeButton setImage:[UIImage imageNamed:@"xihuan2@2x"] forState:UIControlStateNormal];
                self.newsShowView.likeButton.userInteractionEnabled = NO;
            }
            self.newsShowView.likeCount.text = [NSString stringWithFormat:@"%ld",like];
            if ([self.newsShowView.likeCount.text isEqualToString:@"0"]) {
                self.newsShowView.likeCount.hidden = YES;
            }
        }else{
            
        }
    }];
}

#pragma mark - 登陆按钮方法实现
- (void)loginButtonAction
{
    [AVUser logInWithUsernameInBackground:self.newsShowView.usernameTF.text password:self.newsShowView.passwordTF.text block:^(AVUser *user, NSError *error) {
        if (user) {
            if (_differentEventNumber == 1) {
                //收藏方法
                [[NSNotificationCenter defaultCenter] postNotificationName:@"collectState" object:self.newsShowView.rightButton];
                AVUser *currentUser = [AVUser currentUser];
                NSString *string = [NSString stringWithFormat:@"%@isFirstLogin",currentUser.username];
                NSInteger number = [[LeanCloudService shareService] isFirstLoginWithKey:string];
                if (number == 1) {
                    NSMutableArray *array = [NSMutableArray array];
                    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.webTitle,@"title",self.webViewUrl,@"url", nil];
                    [array addObject:dic];
                    [currentUser setObject:array forKey:@"BasketBall"];
                    [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        
                    }];
                    [[LeanCloudService shareService] setIsFirstLoginWithNumber:2 andKye:string];
                    [[LeanCloudService shareService] synchronize];
                }else{
                    NSMutableArray *array = [NSMutableArray array];
                    array = [currentUser objectForKey:@"BasketBall"];
                    if (self.webTitle == nil) {
                        self.webTitle = [NewsHandle sharedNewsHandle].WebTitle;
                    }
                    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.webTitle,@"title",self.webViewUrl,@"url", nil];
                    [array addObject:dic];
                    [currentUser setObject:array forKey:@"BasketBall"];
                    [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        
                    }];
                }
                //已收藏方法(收藏过得再次进入不在能收藏)
                AVObject *collect = [AVObject objectWithoutDataWithClassName:@"celloct" objectId:@"56a1a8d4128fe1005141c0f0"];
                NSString *collectStr = [NSString stringWithFormat:@"collect%@%@",self.model.iD,currentUser.username];
                [collect setObject:@"isCollect" forKey:collectStr];
                [collect saveInBackground];

            }else if (_differentEventNumber == 2){
                //执行喜欢方法
            }else{
                //讨论
                TalkingViewController *talkVC = [[TalkingViewController alloc]init];
                [self presentViewController:talkVC animated:YES completion:nil];
            }
            [LeanCloudService shareService].nowLoginUserName = self.newsShowView.usernameTF.text;
            //登陆成功 关闭登陆窗口
            self.newsShowView.usernameTF.text = nil;
            self.newsShowView.passwordTF.text = nil;
            self.newsShowView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), SCREEN_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
            //释放响应者
            [self.newsShowView endEditing:YES];
        }else{
            self.newsShowView.usernameTF.text = nil;
            self.newsShowView.passwordTF.text = nil;
            [self loginFiled];
        }
    }];
}
#pragma mark - 注册按钮方法实现
- (void)registButtonAction
{
    RegistViewController *registVC = [[RegistViewController alloc]init];
    [self presentViewController:registVC animated:YES completion:nil];
}
#pragma mark - 忘记密码按钮方法实现
- (void)findPWDButtonAction
{
    FindPWDViewController *findVC = [[FindPWDViewController alloc]init];
    [self presentViewController:findVC animated:YES completion:nil];
}

#pragma mark - 通知方法
- (void)changeCollectState:(NSNotification *)sender
{
    [self.newsShowView.rightButton setImage:[UIImage imageNamed:@"shoucangle2@2x"] forState:UIControlStateNormal];
}
#pragma mark ---talkButtonAction
-(void)talkButtonAction:(UIButton *)sender
{
    //判断状态
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        [UIView animateWithDuration:0.5 animations:^{
            self.newsShowView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), 100 * LAYOUT_SIZE_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
        }];
        _differentEventNumber = 3;
    }else{
        TalkingViewController *talkVC = [[TalkingViewController alloc]init];
        talkVC.webID = [self.model.iD integerValue];
        [self presentViewController:talkVC animated:YES completion:nil];
    }
    
}
#pragma mark - 手势方法实现
- (void)edgeGR
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)panGR
{
    [UIView animateWithDuration:0.5 animations:^{
        self.newsShowView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), SCREEN_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
    }];
}
#pragma mark ---自定义导航栏左侧按钮点击事件
-(void)leftButtonAction:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark ---自定义导航栏右侧收藏按钮点击事件
-(void)rightButtonAction:(UIButton *)sender
{
    
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        [UIView animateWithDuration:0.5 animations:^{
            self.newsShowView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), 100 * LAYOUT_SIZE_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
        }];
        _differentEventNumber = 1;
    }else{
        [self.newsShowView.rightButton setImage:[UIImage imageNamed:@"shoucangle2@2x"] forState:UIControlStateNormal];
        NSMutableArray *array = [NSMutableArray array];
        array = [currentUser objectForKey:@"News"];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.webTitle,@"title",self.webViewUrl,@"url", nil];
        [array addObject:dic];
        [currentUser setObject:array forKey:@"News"];
        [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            
        }];
        
        NSString *string = [NSString stringWithFormat:@"%@isFirstLogin",currentUser.username];
        NSInteger number = [[LeanCloudService shareService] isFirstLoginWithKey:string];
        if (number == 1) {
            NSMutableArray *array = [NSMutableArray array];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.webTitle,@"title",self.webViewUrl,@"url", nil];
            [array addObject:dic];
            [currentUser setObject:array forKey:@"BasketBall"];
            [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            }];
            [[LeanCloudService shareService] setIsFirstLoginWithNumber:2 andKye:string];
            [[LeanCloudService shareService] synchronize];
        }else{
            NSMutableArray *array = [NSMutableArray array];
            array = [currentUser objectForKey:@"BasketBall"];
            if (self.webTitle == nil) {
                self.webTitle = [NewsHandle sharedNewsHandle].WebTitle;
            }
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.webTitle,@"title",self.webViewUrl,@"url", nil];
            [array addObject:dic];
            [currentUser setObject:array forKey:@"BasketBall"];
            [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            }];
        }
        //已收藏方法(收藏过得再次进入不在能收藏)
        AVObject *collect = [AVObject objectWithoutDataWithClassName:@"celloct" objectId:@"56a1a8d4128fe1005141c0f0"];
        NSString *collectStr = [NSString stringWithFormat:@"collect%@%@",self.model.iD,currentUser.username];
        [collect setObject:@"isCollect" forKey:collectStr];
        [collect saveInBackground];

    }
    
    
}
#pragma mark --- 喜欢按钮点击事件
-(void)likeButtonAction:(UIButton *)sender
{
    //判断状态
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        [UIView animateWithDuration:0.5 animations:^{
            self.newsShowView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), 100 * LAYOUT_SIZE_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
        }];
        _differentEventNumber = 2;
    }else{
        [self.newsShowView.likeButton setImage:[UIImage imageNamed:@"xihuan2@2x"] forState:UIControlStateNormal];
        AVObject *object = [AVObject objectWithoutDataWithClassName:@"NewsLike" objectId:@"569f4ecad342d30053c1acf3"];
        NSString *likeCount = [NSString stringWithFormat:@"likeCount%@",self.model.iD];
        NSString *islike = [NSString stringWithFormat:@"isLike%@%@",self.model.iD,currentUser.username];
        [object setObject:[NSNumber numberWithInteger:1] forKey:likeCount];
        [object setObject:@"like" forKey:islike];
        [object incrementKey:likeCount];
        [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                
            }else{
                
            }
        }];
    }
    
}

#pragma mark - 监控webView方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //点击
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        //通过点击 获取网址
        NSString *url = request.URL.absoluteString;
        //判断网址长度 分辨点击的是微信微博还是其他webview
        //当网址小于100长度时  点击的是其他的webview
        if (url.length < 100) {
            //根据网址 获取最后九位的ID
            url = [url substringFromIndex:url.length - 9];
            //通过ID来拼接webview网址
            NSString *webUrl = [NSString stringWithFormat:@"http://api.basketball.app887.com/article.html?id=%@",url];
//
            //初始化自己的webView  不需要根据每个ID都创建webview
            NewsShowViewController *webVC = [[NewsShowViewController alloc] init];
            UINavigationController *webNC = [[UINavigationController alloc] initWithRootViewController:webVC];
            //让webView后面拼接的ID等于上面获取到的ID
            webVC.webViewUrl = webUrl;
            webVC.model.iD = url;
            //初始化之后图片为空 重新赋值
            self.shareImage = [UIImage imageNamed:@"app"];
            [[NewsHandle sharedNewsHandle] loadDataWithWebView:url withBlock:^(BOOL isFinished) {
                if (isFinished) {
                    [self.newsShowView.newsShowWebview reloadInputViews];
                }
            }];
            webVC.modalTransitionStyle = 1;
            [self presentViewController:webNC animated:YES completion:nil];
        }else{
            //通过网址长度大于100 得到网址最后的tapy值(1,2,3)判断点击的是分享微信按钮,还是转发朋友圈按钮,或者是转发微博按钮
            url = [url substringFromIndex:url.length - 1];
//
            if ([url isEqualToString:@"3"]) {
                //转发微信
                [self shareToWechat];
            }else if ([url isEqualToString:@"2"]){
                //转发朋友圈
                [self shareToWechatFriend];
            }else{
                //转发微博
                [self shareToSina];
                
            }
        }
    }
    return YES;
}
#pragma mark ---分享微信
- (void)shareToWechat
{
    if (self.webTitle == nil) {
        self.webTitle = [NewsHandle sharedNewsHandle].WebTitle;
    }
    [UMSocialData defaultData].extConfig.wechatSessionData.url = self.model.url;
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession] content:self.webTitle image:self.shareImage location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
        if (response.responseCode == UMSResponseCodeSuccess) {
            
        }
    }];
    
}
#pragma mark - 转发朋友圈
- (void)shareToWechatFriend
{
    if (self.webTitle == nil) {
        self.webTitle = self.model.title;
    }
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = self.model.url;
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline] content:self.webTitle image:self.shareImage location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
        if (response.responseCode == UMSResponseCodeSuccess) {
            
        }
    }];
}
#pragma mark - 转发微博
- (void)shareToSina
{
    if (self.webTitle == nil) {
        self.webTitle = self.model.title;
    }
    //切换界面的时候会初始化Controller 所以self.webTitle为空  当为空得时候 加载数据 去除title然后在赋值
    self.webTitle = [NSString stringWithFormat:@"%@%@",self.webTitle,self.model.url];
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToSina] content:self.webTitle image:self.shareImage location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
        if (response.responseCode == UMSResponseCodeSuccess) {
            
        }
    }];
}
#pragma mark - 界面将要消失方法
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    //添加点击方法
    [self.newsShowView.shareButton addTarget:self action:@selector(shareOtherone) forControlEvents:UIControlEventTouchUpInside];
}


#pragma mark - 分享按钮方法
- (void)shareOtherone
{
    if (self.webTitle == nil) {
        self.webTitle = self.model.title;
    }
    //切换界面的时候会初始化Controller 所以self.webTitle为空  当为空得时候 加载数据 去除title然后在赋值
    [UMSocialData defaultData].extConfig.qqData.url = self.model.url;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = self.model.url;
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5693101667e58e370a00054f"
                                      shareText:self.webTitle
                                     shareImage:self.shareImage
                                shareToSnsNames:@[UMShareToSina,UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite]
                                       delegate:nil];
}

#pragma mark - 提示框(登录失败)
- (void)loginFiled
{
    CGFloat verison = [[[UIDevice currentDevice]systemVersion]floatValue];
    if (verison >= 8.0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登录失败" message:@"请确认账号和密码是否匹配" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
        
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"登录失败" message:@"请确认账号和密码是否匹配" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [alertView show];
        
        [self performSelector:@selector(aftertimeAction:) withObject:alertView afterDelay:2.0];
    }
    
}

#pragma mark - 延迟2秒方法
- (void)aftertimeAction:(UIAlertView *)sender
{
    
    [sender dismissWithClickedButtonIndex:0 animated:YES];
    
}

#pragma mark - 处理内存问题
-(void)dealloc {
    
    self.newsShowView.newsShowWebview.delegate = nil;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
